<template>
	<div class="wrapper">
		<!-- header部分 -->
		<header>
			<p>我的订单</p>
		</header>
		
		<!-- 订单列表部分 -->
		<div class="order-content">
			<!-- 未支付订单 -->
			<section class="order-section">
				<h3>未支付订单</h3>
				<div v-if="unpaidOrders.length === 0" class="no-orders">
					<p>暂无未支付订单</p>
				</div>
				<ul v-else class="order-list">
					<li v-for="order in unpaidOrders" :key="order.id" class="order-item">
						<div class="order-header">
							<div class="order-shop">
								<span class="shop-name">{{ order.business?.businessName || '未知商家' }}</span>
								<span class="order-status unpaid">待支付</span>
							</div>
							<div class="order-amount">
								<span class="amount">¥{{ order.orderTotal?.toFixed(2) || '0.00' }}</span>
								<button class="pay-btn" @click="goToPayment(order.id)">去支付</button>
							</div>
						</div>
						
						<div class="order-details">
							<button class="toggle-details" @click="toggleOrderDetails(order)">
								<i class="fa" :class="order.showDetails ? 'fa-caret-up' : 'fa-caret-down'"></i>
								订单详情
							</button>
							
							<div v-if="order.showDetails" class="details-content">
								<div class="order-info">
									<p><strong>订单号:</strong> {{ order.id }}</p>
									<p><strong>下单时间:</strong> {{ formatDate(order.createTime) }}</p>
									<p><strong>配送地址:</strong> {{ order.deliveryAddress?.address || '未设置' }}</p>
								</div>
								
								<div class="order-items">
									
									<div class="order-summary">
										<div class="summary-item">
											<span>配送费:</span>
											<span>¥{{ order.business?.deliveryPrice?.toFixed(2) || '0.00' }}</span>
										</div>
										<div class="summary-item total">
											<span>订单总额:</span>
											<span>¥{{ order.orderTotal?.toFixed(2) || '0.00' }}</span>
										</div>
									</div>
								</div>
							</div>
						</div>
					</li>
				</ul>
			</section>

			<!-- 已支付订单 -->
			<section class="order-section">
				<h3>已支付订单</h3>
				<div v-if="paidOrders.length === 0" class="no-orders">
					<p>暂无已支付订单</p>
				</div>
				<ul v-else class="order-list">
					<li v-for="order in paidOrders" :key="order.id" class="order-item">
						<div class="order-header">
							<div class="order-shop">
								<span class="shop-name">{{ order.business?.businessName || '未知商家' }}</span>
								<span class="order-status paid">{{ getOrderStatusText(order.orderState) }}</span>
							</div>
							<div class="order-amount">
								<span class="amount">¥{{ order.orderTotal?.toFixed(2) || '0.00' }}</span>
								<button v-if="order.orderState === 2" class="confirm-btn" @click="confirmReceipt(order)">
									确认收货
								</button>
							</div>
						</div>
						
						<div class="order-details">
							<button class="toggle-details" @click="toggleOrderDetails(order)">
								<i class="fa" :class="order.showDetails ? 'fa-caret-up' : 'fa-caret-down'"></i>
								订单详情
							</button>
							
							<div v-if="order.showDetails" class="details-content">
								<div class="order-info">
									<p><strong>订单号:</strong> {{ order.id }}</p>
									<p><strong>配送地址:</strong> {{ order.deliveryAddress?.address || '未设置' }}</p>
									<p><strong>订单状态:</strong> {{ getOrderStatusText(order.orderState) }}</p>
								</div>
								
								<div class="order-items">
									
									<div class="order-summary">
										<div class="summary-item">
											<span>配送费:</span>
											<span>¥{{ order.business?.deliveryPrice?.toFixed(2) || '0.00' }}</span>
										</div>
										<div class="summary-item total">
											<span>订单总额:</span>
											<span>¥{{ order.orderTotal?.toFixed(2) || '0.00' }}</span>
										</div>
									</div>
								</div>
							</div>
						</div>
					</li>
				</ul>
			</section>
		</div>

		<!-- 底部菜单部分 -->
		<Footer></Footer>
	</div>
</template>

<script>
import Footer from '../components/Footer.vue';

export default {
	name: 'OrderList',
	components: {
		Footer
	},
	data() {
		return {
			orders: [],
			loading: false,
			error: null
		}
	},
	computed: {
		// 未支付订单：orderState = 0
		unpaidOrders() {
			return this.orders.filter(order => order.orderState === 0);
		},
		// 已支付订单：orderState >= 1
		paidOrders() {
			return this.orders.filter(order => order.orderState >= 1);
		}
	},
	async created() {
		await this.loadOrders();
	},
	methods: {
		// 获取sessionStorage中的用户信息
		getSessionStorage(key) {
			try {
				const item = sessionStorage.getItem(key);
				return item ? JSON.parse(item) : null;
			} catch (error) {
				console.error('获取sessionStorage失败:', error);
				return null;
			}
		},

		// 加载用户订单列表
		async loadOrders() {
			this.loading = true;
			this.error = null;
			
			try {
				const user = this.getSessionStorage('user');
				if (!user || !user.userId) {
					throw new Error('用户未登录，请先登录');
				}

				// 使用新的API接口：GET /api/orders/user/{userId}
				const response = await this.$axios.get(`/api/orders/user/${user.userId}`);
				
				if (response.data.success) {
					this.orders = response.data.data || [];
					// 为每个订单添加显示详情的状态
				} else {
					throw new Error(response.data.message || '获取订单列表失败');
				}
			} catch (error) {
				console.error('加载订单列表失败:', error);
				this.handleError('加载订单列表', error);
			} finally {
				this.loading = false;
			}
		},

		// 加载单个订单详情
		async loadOrderDetails(orderId) {
			try {
				// 使用新的API接口：GET /api/orders/{id}
				const response = await this.$axios.get(`/api/orders/${orderId}`);
				
				if (response.data.success) {
					return response.data.data;
				} else {
					throw new Error(response.data.message || '获取订单详情失败');
				}
			} catch (error) {
				console.error('加载订单详情失败:', error);
				this.handleError('加载订单详情', error);
				return null;
			}
		},

		// 切换订单详情显示
		async toggleOrderDetails(order) {
			// 如果订单详情未加载，则先加载详情
			if (!order.showDetails && (!order.orderItems || order.orderItems.length === 0)) {
				const orderDetails = await this.loadOrderDetails(order.id);
				if (orderDetails) {
					order.orderItems = orderDetails.orderItems || [];
				}
			}
			order.showDetails = !order.showDetails;
		},

		// 去支付
		goToPayment(orderId) {
			this.$router.push({
				path: '/payment',
				query: { orderId: orderId }
			});
		},

		// 查看订单详情
		async viewOrderDetails(order) {
			// 先加载完整的订单详情
			const orderDetails = await this.loadOrderDetails(order.id);
			if (orderDetails) {
				// 更新订单信息
				Object.assign(order, orderDetails);
				order.showDetails = true;
			}
		},

		// 计算商品总额
		calculateItemsTotal(orderItems) {
			if (!orderItems || !Array.isArray(orderItems)) return 0;
			
			return orderItems.reduce((total, item) => {
				const price = item.food?.foodPrice || 0;
				const quantity = item.quantity || 0;
				return total + (price * quantity);
			}, 0);
		},

		// 格式化日期
		formatDate(dateString) {
			if (!dateString) return '未知时间';
			
			try {
				const date = new Date(dateString);
				return date.toLocaleString('zh-CN', {
					year: 'numeric',
					month: '2-digit',
					day: '2-digit',
					hour: '2-digit',
					minute: '2-digit'
				});
			} catch (error) {
				return dateString;
			}
		},

		// 获取订单状态文本
		getOrderStatusText(orderState) {
			const statusMap = {
				0: '未支付',
				1: '未支付',
				2: '已支付',
				3: '已完成',
			};
			return statusMap[orderState] || '未知状态';
		},

		// 确认收货
		async confirmReceipt(order) {
			if (!confirm(`确认收到 ${order.business?.businessName || '商家'} 的商品？\n确认后资金将转给商家。`)) {
				return;
			}

			try {
				const user = this.getSessionStorage('user');
				if (!user || !user.userId) {
					alert('用户未登录，请重新登录');
					this.$router.push('/login');
					return;
				}

				// 获取买家钱包ID
				const buyerWalletResponse = await this.$axios.get(`/api/virtual-wallets/user/${user.userId}`);
				if (!buyerWalletResponse.data.success || !buyerWalletResponse.data.data) {
					alert('获取买家钱包信息失败');
					return;
				}
				const buyerWalletId = buyerWalletResponse.data.data.walletId;

				// 获取卖家（商家）钱包ID
				// 假设商家的userId存储在business对象中，或者商家有walletId
				// 这里需要根据实际情况调整
				let sellerWalletId = 1; // 默认值，实际应从商家信息获取
				
				// 如果商家信息中有userId，获取其钱包ID
				if (order.business?.userId) {
					const sellerWalletResponse = await this.$axios.get(`/api/virtual-wallets/user/${order.business.userId}`);
					if (sellerWalletResponse.data.success && sellerWalletResponse.data.data) {
						sellerWalletId = sellerWalletResponse.data.data.walletId;
					}
				}

				// 调用确认收货接口
				const confirmResponse = await this.$axios.post('/api/virtual-wallets/confirm-order', null, {
					params: {
						buyerWalletId: buyerWalletId,
						sellerWalletId: sellerWalletId,
						amount: order.orderTotal,
						orderId: order.id
					}
				});

				if (confirmResponse.data.success) {
					// 更新订单状态为已完成(3)
					await this.$axios.put(`/api/orders/${order.id}/state`, null, {
						params: { state: 3 }
					});

					alert('确认收货成功！资金已转给商家。');
					
					// 重新加载订单列表
					await this.loadOrders();
				} else {
					alert('确认收货失败: ' + (confirmResponse.data.message || '未知错误'));
				}
			} catch (error) {
				console.error('确认收货失败:', error);
				if (error.response?.data?.message) {
					alert('确认收货失败: ' + error.response.data.message);
				} else {
					alert('确认收货失败，请稍后重试');
				}
			}
		},

		// 错误处理
		handleError(operation, error) {
			let errorMessage = `${operation}失败`;
			
			if (error.response) {
				switch (error.response.status) {
					case 401:
						errorMessage = '用户未登录或会话已过期';
						this.$router.push('/login');
						break;
					case 404:
						errorMessage = '请求的资源不存在';
						break;
					case 500:
						errorMessage = '服务器内部错误';
						break;
					default:
						if (error.response.data?.message) {
							errorMessage = error.response.data.message;
						}
				}
			} else if (error.message) {
				errorMessage = error.message;
			}
			
			this.error = errorMessage;
			alert(errorMessage);
		}
	}
}
</script>

<style scoped>
.wrapper {
	width: 100%;
	min-height: 100vh;
	background-color: #f5f5f5;
}

/* header部分 */
header {
	width: 100%;
	height: 12vw;
	background-color: #0097FF;
	color: #fff;
	font-size: 4.8vw;
	position: fixed;
	left: 0;
	top: 0;
	z-index: 1000;
	display: flex;
	justify-content: center;
	align-items: center;
}

/* 订单内容区域 */
.order-content {
	padding-top: 12vw;
	padding-bottom: 14vw;
}

.order-section {
	margin-bottom: 20px;
	background-color: white;
}

.order-section h3 {
	margin: 0;
	padding: 15px 20px;
	font-size: 1.2rem;
	color: #333;
	border-bottom: 1px solid #eee;
	background-color: #fafafa;
}

.no-orders {
	padding: 40px 20px;
	text-align: center;
	color: #999;
	font-size: 1rem;
}

/* 订单列表样式 */
.order-list {
	list-style: none;
	padding: 0;
	margin: 0;
}

.order-item {
	border-bottom: 1px solid #eee;
	padding: 15px 20px;
}

.order-item:last-child {
	border-bottom: none;
}

.order-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	margin-bottom: 10px;
}

.order-shop {
	display: flex;
	align-items: center;
	gap: 10px;
}

.shop-name {
	font-size: 1.1rem;
	font-weight: bold;
	color: #333;
}

.order-status {
	padding: 2px 8px;
	border-radius: 12px;
	font-size: 0.8rem;
	font-weight: bold;
}

.order-status.unpaid {
	background-color: #ff4757;
	color: white;
}

.order-status.paid {
	background-color: #38CA73;
	color: white;
}

.order-amount {
	display: flex;
	align-items: center;
	gap: 10px;
}

.amount {
	font-size: 1.2rem;
	font-weight: bold;
	color: #ff4757;
}

.pay-btn, .view-btn, .confirm-btn {
	padding: 6px 12px;
	border: none;
	border-radius: 4px;
	font-size: 0.9rem;
	cursor: pointer;
	transition: all 0.3s;
}

.pay-btn {
	background-color: #0097FF;
	color: white;
}

.pay-btn:hover {
	background-color: #0085e0;
}

.view-btn {
	background-color: #38CA73;
	color: white;
}

.view-btn:hover {
	background-color: #2db863;
}

.confirm-btn {
	background-color: #38CA73;
	color: white;
}

.confirm-btn:hover {
	background-color: #2db863;
}

/* 订单详情样式 */
.order-details {
	margin-top: 10px;
}

.toggle-details {
	width: 100%;
	padding: 8px 0;
	background: none;
	border: none;
	border-top: 1px dashed #ddd;
	color: #666;
	font-size: 0.9rem;
	cursor: pointer;
	display: flex;
	align-items: center;
	gap: 5px;
}

.toggle-details:hover {
	color: #0097FF;
}

.details-content {
	padding: 15px 0;
}

.order-info {
	margin-bottom: 15px;
}

.order-info p {
	margin: 5px 0;
	font-size: 0.9rem;
	color: #666;
}

.order-items h4 {
	margin: 0 0 10px 0;
	font-size: 1rem;
	color: #333;
}

.order-item-detail {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 5px 0;
	border-bottom: 1px solid #f0f0f0;
}

.order-item-detail:last-child {
	border-bottom: none;
}

.item-name {
	flex: 1;
	font-size: 0.9rem;
}

.item-quantity {
	margin: 0 10px;
	color: #666;
	font-size: 0.9rem;
}

.item-price {
	font-weight: bold;
	color: #ff4757;
}

.no-items {
	text-align: center;
	padding: 10px;
	color: #999;
	font-size: 0.9rem;
}

.order-summary {
	margin-top: 15px;
	padding-top: 15px;
	border-top: 1px solid #eee;
}

.summary-item {
	display: flex;
	justify-content: space-between;
	align-items: center;
	margin: 5px 0;
	font-size: 0.9rem;
}

.summary-item.total {
	font-weight: bold;
	font-size: 1rem;
	color: #ff4757;
	border-top: 1px solid #eee;
	padding-top: 5px;
	margin-top: 10px;
}

/* 加载状态 */
.loading {
	text-align: center;
	padding: 40px 20px;
	color: #666;
	font-size: 1rem;
}

.error {
	text-align: center;
	padding: 20px;
	color: #ff4757;
	background-color: #ffeaea;
	margin: 10px 20px;
	border-radius: 4px;
}

/* 响应式设计 */
@media (max-width: 768px) {
	.order-header {
		flex-direction: column;
		align-items: flex-start;
		gap: 10px;
	}
	
	.order-amount {
		width: 100%;
		justify-content: space-between;
	}
	
	.shop-name {
		font-size: 1rem;
	}
	
	.amount {
		font-size: 1.1rem;
	}
	
	.pay-btn, .view-btn {
		padding: 8px 15px;
		font-size: 0.9rem;
	}
}

@media (max-width: 480px) {
	.order-item {
		padding: 10px 15px;
	}
	
	.order-section h3 {
		padding: 10px 15px;
		font-size: 1.1rem;
	}
	
	.shop-name {
		font-size: 0.9rem;
	}
	
	.order-status {
		font-size: 0.7rem;
		padding: 1px 6px;
	}
}
</style>